package com.tnovoselec.android.favorites.db;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.tnovoselec.android.favorites.entity.FavoritesDto;
import com.tnovoselec.android.orm.apptools.OrmLiteSqliteOpenHelper;

/**
 * Title: Android Framework - Favorites <br />
 * Copyright: Copyright (c) 2011 <br />
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0 FavoritesDatabaseHelper is used to create/upgrade/destroy tables
 *        associated with given database. It requires database name, database
 *        version, create queries (and triggers if any) and model class which
 *        are used
 */

public abstract class FavoritesDatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static final String TAG = FavoritesDatabaseHelper.class.getSimpleName();

    public FavoritesDatabaseHelper(Context context, String databaseName, CursorFactory factory, int databaseVersion) {
	super(context, databaseName, factory, databaseVersion);
    }

    public abstract String getDatabaseName();

    public abstract int getDatabaseVersion();

    public abstract List<String> getCreateQueries();

    public abstract List<Class> getDtoClasses();

    /**
     * Creates tables and triggers associated with the given database
     */
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource1) {

	try {

	    for (String createQuery : getCreateQueries()) {
		database.execSQL(createQuery);
	    }

	} catch (Exception ex) {

	    Log.e(TAG, ex.getMessage());
	}
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {

	try {
	    for (Class<FavoritesDto> clazz : getDtoClasses()) {
		TableUtils.dropTable(connectionSource, clazz, true);
	    }
	    onCreate(database, connectionSource);
	} catch (SQLException ex) {
	    Log.e(TAG, "Can't drop table: ", ex);
	    throw new RuntimeException(ex);
	}

    }
}
